<template>
  <div class="excel-exporter">
    <button @click="exportToExcel" class="export-btn">
      {{ buttonText }}
    </button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

export default {
  name: 'ExcelExporter',
  props: {
    data: {
      type: Array,
      required: true
    },
    fileName: {
      type: String,
      default: 'exported-data'
    },
    buttonText: {
      type: String,
      default: '导出Excel'
    }
  },
  methods: {
    exportToExcel() {
      try {
        // 创建工作簿
        const wb = XLSX.utils.book_new()
        
        // 将数据转换为工作表
        const ws = XLSX.utils.json_to_sheet(this.data)
        
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        
        // 生成Excel文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
        
        // 保存文件
        const blob = new Blob([wbout], { type: 'application/octet-stream' })
        saveAs(blob, `${this.fileName}.xlsx`)
        
        this.$emit('export-success')
      } catch (error) {
        console.error('导出Excel失败:', error)
        this.$emit('export-error', error)
      }
    }
  }
}
</script>

<style scoped>
.excel-exporter {
  display: inline-block;
}

.export-btn {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.export-btn:hover {
  background-color: #45a049;
}

.export-btn:active {
  background-color: #3d8b40;
}
</style> 